local jLootz = jLootz
local lib = jLootz:GetModule("Group")

local function RollFrame_OnUpdate(self)
	local timeleft, timer = GetLootRollTimeLeft(self.id), self.timer
	local min, max = timer:GetMinMaxValues()
	if timeleft < min or timeleft > max then
		timeleft = min
	end
	timer:SetValue(timeleft)
end

local function RollFrameButton_OnClick(self)
	RollOnLoot(self:GetParent().id, self.roll)
end

local function RollFrameButton_OnEnter(self)
	local GameTooltip = GameTooltip
	GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
	GameTooltip:SetText(self.desc)
end

local function RollFrameButton_OnLeave(self)
	local GameTooltip = GameTooltip
	if GameTooltip:IsOwned(self) then
		GameTooltip:Hide()
	end
end

local function MakeRollFrameButton(parent, roll, desc, type)
	local button = CreateFrame("Button", nil, parent)
	
	button.roll, button.desc = roll, desc
	button:SetScript("OnClick", RollFrameButton_OnClick)
	button:SetScript("OnEnter", RollFrameButton_OnEnter)
	button:SetScript("OnLeave", RollFrameButton_OnLeave)

	button:SetNormalTexture("Interface\\Buttons\\UI-GroupLoot-"..type.."-Up")
	button:SetPushedTexture("Interface\\Buttons\\UI-GroupLoot-"..type.."-Highlight")
	button:SetHighlightTexture("Interface\\Buttons\\UI-GroupLoot-"..type.."-Down")
	
	button:SetWidth(26)
	button:SetHeight(26)

	return button
end

local buttons = {
	{0, PASS, "Pass"},
	{1, NEED, "Dice"},
	{2, GREED, "Coin"},
}

function lib:MakeRollFrame(parent)
	local frame = CreateFrame("Frame", nil, parent)
	
	frame.texture = frame:CreateTexture(nil, "ARTWORK")
	frame.name = frame:CreateFontString(nil, "ARTWORK")
	frame.count = frame:CreateFontString(nil, "OVERLAY")
	frame.bop = frame:CreateFontString(nil, "OVERLAY")
	
	frame.timer = CreateFrame("StatusBar", nil, frame)
	
	local prev
	for _, info in ipairs(buttons) do
		local rollId, rollDesc, rollType = unpack(info)
		local button = MakeRollFrameButton(frame, rollId, rollDesc, rollType)
		if prev then
			button:SetPoint("LEFT", prev, "RIGHT", 2, 0)
		else
			button:SetPoint("LEFT", 2, 0)
		end
		self[rollType] = button
		prev = button
	end
	
	frame:SetScript("OnUpdate", RollFrame_OnUpdate)
	
	return frame
end

function lib:FillRollFrame(frame, id, timeleft)
	local texture, name, count, quality, bop = GetLootRollItemInfo(id)

	frame.id = id
	
	frame.texture:SetTexture(texture)
	frame.name:SetText(name)
	if not count or count == 1 then
		frame.count:Hide()
	else
		frame.count:SetText(text)
		frame.count:Show()
	end
	if bop then
		frame.bop:Show()
	else
		frame.bop:Hide()
	end
	frame.timer:SetMinMaxValues(0, timeleft)
end

function lib:GetRollFrame()
	local frames = self.frames
	local n = (frames.count or 0) + 1
	local f = frames[n]
	if not f then
		f = self:MakeRollFrame()
	end
	frames.count = n
	f:Show()
	return f
end

function lib:ClearRollFrames()
	local frames = self.frames
	for i = 1, (frames.count or 0) do
		frames[i]:Hide()
	end
	frames.count = nil
end
